import { defineStore } from 'pinia';
import { getUnreadNum } from '@/api/notice';

export const useNoticeStore = defineStore('notice', {
  state: () => ({
    unreadCount: 0 as number,
    loading: false,
  }),
  actions: {
    async fetchUnreadNum() {
      if (this.loading) return this.unreadCount;
      this.loading = true;
      try {
        const res = await getUnreadNum();
        // 后端常用 code 可能是字符串 '200' 或数字 200，这里统一转为字符串判断
        if (res && String(res.code) === '200') {
          this.unreadCount = Number(res.data ?? 0);
        }
        return this.unreadCount;
      } finally {
        this.loading = false;
      }
    },
    setUnreadCount(count: number) {
      this.unreadCount = Number(count || 0);
    },
  },
});
